//
//  Untitled.swift
//  PLDownload
//
//  Created by bin hu on 2025/7/7.
//

import Foundation

class FileSystemManager {
    
    static let shared = FileManager()
    private let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    private let downloadsFolder = "Downloads"
    private let tempFolder = "Temp"
    
    init() {
        createDownloadsFolder()
    }
    
    private func createDownloadsFolder() {
        let downloadsURL = documentsURL.appendingPathComponent(downloadsFolder)
        if !FileManager.default.fileExists(atPath: downloadsURL.path) {
            try? FileManager.default.createDirectory(at: downloadsURL, withIntermediateDirectories: true)
        }
    }
    
    func localPath(for task: DownloadTask) -> URL {
        let folder = documentsURL.appendingPathComponent(downloadsFolder)
        let fileName = "\(task.title).\(task.fileType)"
        return folder.appendingPathComponent(fileName)
    }
    
    func createTempDirectory(for task: DownloadTask) -> URL {
        let tempURL = documentsURL
            .appendingPathComponent(tempFolder)
            .appendingPathComponent(task.id.uuidString)
        
        if !FileManager.default.fileExists(atPath: tempURL.path) {
            try? FileManager.default.createDirectory(at: tempURL, withIntermediateDirectories: true)
        }
        
        return tempURL
    }
    
    func clearTempDirectory(for task: DownloadTask) {
        let tempURL = documentsURL
            .appendingPathComponent(tempFolder)
            .appendingPathComponent(task.id.uuidString)
        
        if FileManager.default.fileExists(atPath: tempURL.path) {
            try? FileManager.default.removeItem(at: tempURL)
        }
    }
    
    func openFile(at url: URL) {
        #if os(macOS)
        NSWorkspace.shared.selectFile(url.path, inFileViewerRootedAtPath: url.deletingLastPathComponent().path)
        #else
        // 在iOS上打开文件预览
        #endif
    }
    
    
    func moveToPermanentLocation(from tempPath: URL,
                                 to finalPath: URL) throws {
        // 检查磁盘空间
        guard hasEnoughSpace(for: fileSize) else {
            throw DownloadError.insufficientDiskSpace
        }
        
        // 安全文件转移
        try FileManager.default.moveItem(
            at: tempPath,
            to: finalPath
        )
        
        // 添加到下载完成列表
        task.state = .completed
    }
}
